
package com.chainyoung.common.http.interceptor;

import android.Manifest;
import android.content.Context;
import android.support.v4.content.ContextCompat;

import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.PhoneUtils;
import com.chainyoung.common.utils.SPUtil;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class PhoneInfoInterceptor implements Interceptor {

    private Context context;

    public PhoneInfoInterceptor(Context context) {
        this.context = context;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder mNewBuilder = chain.request().newBuilder();

        HttpUrl url = chain.request().url().newBuilder()
                .addQueryParameter("lang", PhoneUtils.getSystemLanguage().startsWith("zh")?"zh-cn":"en-us")
                .build();
        Request.Builder mHeader = mNewBuilder.addHeader(LibConstant.VERSION, AppUtils.getAppVersionCode(context) + "").
                addHeader(LibConstant.VERSION_NAME, AppUtils.getAppVersionName(context)).addHeader(LibConstant.DEVICE_MODEL,
                PhoneUtils.getSystemModel())
                .addHeader(LibConstant.DEVICE_BRAND, PhoneUtils.getDeviceBrand())
                .addHeader(LibConstant.PLATFORM, "Android_" + PhoneUtils.getSystemVersion())
                .url(url);
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PERMISSION_GRANTED) {
            mHeader.addHeader(LibConstant.DEVICE_ID, PhoneUtils.getIMEI(context));
        }
        Request mRequest = mHeader.build();
        return chain.proceed(mRequest);
    }
}
